package com.apes.scm.account.account.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.Arith;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.StringUtil;
import com.apes.scm.account.account.model.InventoryBatch;
import com.apes.scm.account.account.repository.InventoryBatchDao;
import com.apes.scm.account.account.repository.InventoryBatchRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by lishikun on 2020/11/26 19:54
 */
@Service("inventoryBatchService")
public class InventoryBatchService extends DomainService {

    @Autowired
    InventoryBatchDao inventoryBatchDao;

    @Autowired
    private InventoryBatchRepository inventoryBatchRepository;

    public JSONObject queryInventoryAge(SimpleRequest request) {
        com.alibaba.fastjson.JSONObject param = new JSONObject();
        param.put("SIZE", request.get("size"));
        param.put("PAGE", request.get("page"));
        PartyRole person = (PartyRole) getPerson(request);
        person.getParty().getId();
        JSONObject object = new JSONObject();
        List<Map> condition = (List<Map>) request.get("condition");
        JSONArray tableHeader = new JSONArray();
        String showType = "";
        String countType = "";
        this.BuildHander(tableHeader, condition);
        for (int i = 0; i < condition.size(); i++) {
            if ("countType".equals(condition.get(i).get("field"))) {
                param.put("countType", condition.get(i).get("value").toString());
                countType = condition.get(i).get("value").toString();
            } else if ("showType".equals(condition.get(i).get("field").toString()))
                showType = condition.get(i).get("value").toString();
        }


        List<Map> array = null;


        try {
            array = inventoryBatchDao.queryInventoryAge(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        object.put("tableHeader", tableHeader);
        object.put("content", array);
        object.put("total", inventoryBatchDao.countInventoryAge(param).get(0).get("COUNT"));
        object.put("pages", 2);
        return object;

    }

    public void BuildHander(JSONArray hander, List<Map> condition) {
        String showType = "";
        String countType = "";

        for (int i = 0; i < condition.size(); i++) {
            if ("countType".equals(condition.get(i).get("field"))) {
                countType = condition.get(i).get("value").toString();
            }
            if ("showType".equals(condition.get(i).get("field").toString()))
                showType = condition.get(i).get("value").toString();
        }

        // 统计维度
        if ("supplier".equals(countType)) {
            Map SUPPLIER_ID = MapUtil.mapper("field", "SUPPLIER_ID",
                    "headerName", "供应商编码", "width", 120
            );
            Map SUPPLIER_NAME = MapUtil.mapper("field", "SUPPLIER_NAME",
                    "headerName", "供应商名称", "width", 120
            );
            hander.add(SUPPLIER_ID);
            hander.add(SUPPLIER_NAME);
        } else if ("company".equals(countType)) {
            Map COMPANY_ID = MapUtil.mapper("field", "COMPANY_ID",
                    "headerName", "公司编码", "width", 120
            );
            Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                    "headerName", "公司名称", "width", 120
            );
            hander.add(COMPANY_ID);
            hander.add(COMPANY_NAME);
        } else if ("classify".equals(countType)) {
            Map CLASSIFY_ID = MapUtil.mapper("field", "CLASSIFY_ID",
                    "headerName", "品类编码", "width", 120
            );
            Map CLASSIFY_NAME = MapUtil.mapper("field", "CLASSIFY_NAME",
                    "headerName", "品类名称", "width", 150
            );
            hander.add(CLASSIFY_ID);
            hander.add(CLASSIFY_NAME);
        } else if ("product".equals(countType)) {
            Map PRODUCT_ID = MapUtil.mapper("field", "PRODUCT_ID",
                    "headerName", "商品编码", "width", 120
            );
            Map PRODUCT_NAME = MapUtil.mapper("field", "PRODUCT_NAME",
                    "headerName", "商品名称", "width", 150
            );
            hander.add(PRODUCT_ID);
            hander.add(PRODUCT_NAME);
        } else if ("brand".equals(countType)) {
            Map BRAND_ID = MapUtil.mapper("field", "BRAND_ID",
                    "headerName", "品牌编码", "width", 120
            );
            Map BRAND_NAME = MapUtil.mapper("field", "BRAND_NAME",
                    "headerName", "品牌名称", "width", 150
            );
            hander.add(BRAND_ID);
            hander.add(BRAND_NAME);
        }


        // 显示维度
        if ("quantity".equals(showType)) {
            // 数量
            Map COUNT_BALANCE_QTY = MapUtil.mapper("field", "COUNT_BALANCE_QTY",
                    "headerName", "总结存数量", "width", 120
            );
            Map SL_15 = MapUtil.mapper("field", "SL_15",
                    "headerName", "0-15天", "width", 120
            );
            Map SL_30 = MapUtil.mapper("field", "SL_30",
                    "headerName", "16-30天", "width", 120
            );
            Map SL_60 = MapUtil.mapper("field", "SL_60",
                    "headerName", "31-60天", "width", 120
            );
            Map SL_90 = MapUtil.mapper("field", "SL_90",
                    "headerName", "61-90天", "width", 120
            );
            Map SL_180 = MapUtil.mapper("field", "SL_180",
                    "headerName", "90-180天", "width", 120
            );
            Map SL_365 = MapUtil.mapper("field", "SL_365",
                    "headerName", "181-365天", "width", 120
            );
            Map SL_365UP = MapUtil.mapper("field", "SL_365UP",
                    "headerName", "365天以上", "width", 120
            );
            hander.add(COUNT_BALANCE_QTY);
            hander.add(SL_15);
            hander.add(SL_30);
            hander.add(SL_60);
            hander.add(SL_90);
            hander.add(SL_180);
            hander.add(SL_365);
            hander.add(SL_365UP);


        } else if ("money".equals(showType)) {
            // 金额
            Map COUNT_NO_TAX_PRICE = MapUtil.mapper("field", "COUNT_NO_TAX_PRICE",
                    "headerName", "不含税总金额", "width", 120
            );
            Map COUNT_TAX_PRICE = MapUtil.mapper("field", "COUNT_TAX_PRICE",
                    "headerName", "含税总金额", "width", 120
            );

            Map SL_15_TAX_PRICE = MapUtil.mapper("field", "SL_15_NO_TAX_PRICE",
                    "headerName", "不含税", "width", 100, "headerGroup", "0-15天"
            );
            Map SL_15_NO_TAX_PRICE = MapUtil.mapper("field", "SL_15_TAX_PRICE",
                    "headerName", "含税", "width", 100, "headerGroup", "0-15天"
            );
            Map SL_30_NO_TAX_PRICE = MapUtil.mapper("field", "SL_30_NO_TAX_PRICE",
                    "headerName", "不含税", "width", 100, "headerGroup", "16-30天"
            );
            Map SL_30_TAX_PRICE = MapUtil.mapper("field", "SL_30_TAX_PRICE",
                    "headerName", "含税", "width", 100, "headerGroup", "16-30天"
            );
            Map SL_60_NO_TAX_PRICE = MapUtil.mapper("field", "SL_60_NO_TAX_PRICE",
                    "headerName", "不含税", "width", 100, "headerGroup", "31-60天"
            );
            Map SL_60_TAX_PRICE = MapUtil.mapper("field", "SL_60_TAX_PRICE",
                    "headerName", "含税", "width", 100, "headerGroup", "31-60天"
            );
            Map SL_90_NO_TAX_PRICE = MapUtil.mapper("field", "SL_90_NO_TAX_PRICE",
                    "headerName", "不含税", "width", 100, "headerGroup", "61-90天"
            );
            Map SL_90_TAX_PRICE = MapUtil.mapper("field", "SL_90_TAX_PRICE",
                    "headerName", "含税", "width", 100, "headerGroup", "61-90天"
            );
            Map SL_180_NO_TAX_PRICE = MapUtil.mapper("field", "SL_180_NO_TAX_PRICE",
                    "headerName", "不含税", "width", 100, "headerGroup", "90-180天"
            );
            Map SL_180_TAX_PRICE = MapUtil.mapper("field", "SL_180_TAX_PRICE",
                    "headerName", "含税", "width", 100, "headerGroup", "90-180天"
            );
            Map SL_365_NO_TAX_PRICE = MapUtil.mapper("field", "SL_365_NO_TAX_PRICE",
                    "headerName", "不含税", "width", 100, "headerGroup", "181-365天"
            );
            Map SL_365_TAX_PRICE = MapUtil.mapper("field", "SL_365_TAX_PRICE",
                    "headerName", "含税", "width", 100, "headerGroup", "181-365天"
            );
            Map SL_365UP_NO_TAX_PRICE = MapUtil.mapper("field", "SL_365UP_NO_TAX_PRICE",
                    "headerName", "不含税", "width", 100, "headerGroup", "365天以上"
            );
            Map SL_365UP_TAX_PRICE = MapUtil.mapper("field", "SL_365UP_TAX_PRICE",
                    "headerName", "含税", "width", 100, "headerGroup", "365天以上"
            );
            hander.add(COUNT_NO_TAX_PRICE);
            hander.add(COUNT_TAX_PRICE);
            hander.add(SL_15_TAX_PRICE);
            hander.add(SL_15_NO_TAX_PRICE);
            hander.add(SL_30_NO_TAX_PRICE);
            hander.add(SL_30_TAX_PRICE);
            hander.add(SL_60_NO_TAX_PRICE);
            hander.add(SL_60_TAX_PRICE);
            hander.add(SL_90_NO_TAX_PRICE);
            hander.add(SL_90_TAX_PRICE);
            hander.add(SL_180_NO_TAX_PRICE);
            hander.add(SL_180_TAX_PRICE);
            hander.add(SL_365_NO_TAX_PRICE);
            hander.add(SL_365_TAX_PRICE);
            hander.add(SL_365UP_NO_TAX_PRICE);
            hander.add(SL_365UP_TAX_PRICE);
        }
    }


    public Page productAnalyse(SimpleRequest request) {
        JSONArray condition = request.getJO().getJSONArray("condition");
        Calendar cal = Calendar.getInstance();
        JSONObject state = (JSONObject) condition.stream().filter(e -> ((JSONObject) e).get("field").equals("state")).findFirst().orElse(new JSONObject());
        condition = condition.stream().filter(e -> !((JSONObject) e).get("field").equals("state")).collect(Collectors.toCollection(JSONArray::new));
        condition.add(MapUtil.mapper("field", "balanceQty", "value", 0, "operator", "GT"));
        String time = state.getString("value");
        List<InventoryBatch> list = inventoryBatchRepository.findAll(JpaDsl.toCriteria(condition));
        if (!time.equals("0")) list = find(list, cal, Integer.valueOf(time));
        List result = new ArrayList<>();
        Map<String, List<InventoryBatch>> map = list.stream().collect(Collectors.groupingBy(e -> e.getProduct().getId()));
        for (Map.Entry<String, List<InventoryBatch>> entry : map.entrySet()) {
            Map<String, List<InventoryBatch>> collect = entry.getValue().stream().collect(Collectors.groupingBy(e -> e.getCompany().getId()));
            for (Map.Entry<String, List<InventoryBatch>> listEntry : collect.entrySet()) {
                List<InventoryBatch> value = listEntry.getValue();
                JSONObject object = new JSONObject();
                object.put("product", "[" + value.get(0).getProduct().getId() + "]" + value.get(0).getProduct().getName());
                object.put("company", "[" + value.get(0).getCompany().getId() + "]" + value.get(0).getCompany().getName());
                object.put("category", "[" + value.get(0).getProduct().getCategory().getId() + "]" + value.get(0).getProduct().getCategory().getName());
                object.put("brand", "[" + value.get(0).getProduct().getBrand().getId() + "]" + value.get(0).getProduct().getBrand().getName());
                object.put("classify", "[" + value.get(0).getProduct().getClassify().getId() + "]" + value.get(0).getProduct().getClassify().getName());
                object.put("classify3", "[" + value.get(0).getProduct().getClassify().getParents().getParents().getId() + "]" + value.get(0).getProduct().getClassify().getParents().getParents().getName());
                object.put("totalPrice", value.stream().mapToDouble(e -> e.getTaxCostPrice() * e.getBalanceQty()).sum());
                object.put("totalQty", value.stream().mapToDouble(e -> e.getBalanceQty()).sum());
                List<InventoryBatch> list90 = find(value, cal, 90);
                object.put("totalPrice90", list90.stream().mapToDouble(e -> e.getTaxCostPrice() * e.getBalanceQty()).sum());
                object.put("totalQty90", list90.stream().mapToDouble(e -> e.getBalanceQty()).sum());
                List<InventoryBatch> list180 = find(value, cal, 180);
                object.put("totalPrice180", list180.stream().mapToDouble(e -> e.getTaxCostPrice() * e.getBalanceQty()).sum());
                object.put("totalQty180", list180.stream().mapToDouble(e -> e.getBalanceQty()).sum());
                List<InventoryBatch> list365 = find(value, cal, 365);
                object.put("totalPrice365", list365.stream().mapToDouble(e -> e.getTaxCostPrice() * e.getBalanceQty()).sum());
                object.put("totalQty365", list365.stream().mapToDouble(e -> e.getBalanceQty()).sum());
                result.add(object);
            }
        }

        return autoPage(request, result);
    }

    public List<InventoryBatch> find(List<InventoryBatch> value, Calendar cal, int time) {
        return value.stream().filter(e -> {
            cal.setTime(e.getPurchaseInDate());
            cal.add(Calendar.DATE, time);
            if (cal.getTime().getTime() < new Date().getTime()) return true;
            return false;
        }).collect(Collectors.toList());
    }

    public Page autoPage(SimpleRequest request, List data) {
        List pageResult;
        int page = Integer.valueOf(request.get("page").toString());
        int size = Integer.valueOf(request.get("size").toString());
        if (data.size() < page * size) return null;
        if (data.size() <= size * (page + 1)) {
            pageResult = data.subList(page * size, data.size());
        } else {
            pageResult = data.subList(page * size, size * (page + 1));
        }
        Pageable pageable = PageRequest.of(request.get("page"), request.get("size"));
        PageImpl pageImpl = new PageImpl<>(pageResult, pageable, data.size());
        return pageImpl;
    }


    /**
     * 解析前端参数
     *
     * @param request
     * @return
     */
    public JSONObject checkRequest(SimpleRequest request) {
        List<Map> filters = new ArrayList<>(request.get("condition"));
        JSONObject model = new JSONObject();
        filters.forEach(filter -> {
            if ("GTE".equals(filter.get("operator")) && ("CREATE_DATE".equals(filter.get("field")) || "PURCHASE_IN_DATE".equals(filter.get("field")))) {
                model.put((String) filter.get("field") + 1, filter.get("value"));
            } else {
                model.put((String) filter.get("field"), filter.get("value"));
            }

        });
        return model;
    }


    /**
     * 解析前端参数
     *
     * @param array filter 参数，解析日期格式
     * @return
     */
    public JSONObject parseCondition(JSONArray array) {
        JSONObject model = new JSONObject();
        array.forEach(v -> {
            JSONObject filter = (JSONObject) v;
            if ("GTE".equals(filter.getString("operator")) && ("CREATE_DATE".equals(filter.getString("field")) || "PURCHASE_IN_DATE".equals(filter.getString("field")))) {
                model.put(filter.getString("field") + "_DATE", filter.getString("value"));//因时间类型的查询条件有两个值，不好区分,所以在字段名后加_DATE
            } else {
                model.put(filter.getString("field"), filter.get("value"));
            }
        });
        return model;
    }

    /**
     * 结余库存查询日月
     *
     * @param request
     * @return
     */
    public JSONObject queryBalance(SimpleRequest request) throws ParseException {
        JSONObject json = request.getJO();
        // 解析传入的条件参数，对日期格式做特殊处理
        JSONObject param = parseCondition(json.getJSONArray("condition"));
        if(!param.get("CREATE_DATE").toString().substring(0,10).equals(param.get("CREATE_DATE_DATE").toString().substring(0,10))) throw new RuntimeException("您选择的日期区间不是同一天，请重新选择！");
        List<Map> resultArray;
        Object count = null;
        String orderField = json.getString("_orderField");
        String replace = StringUtils.isEmpty(orderField) ? null : orderField.replaceAll(";", ",");
        if (Integer.parseInt(param.get("BELONG").toString()) == 1) {
            resultArray = inventoryBatchDao.findBalance(param, request.getPostId(), replace, json.getString("_orderType"), request.get("page"), request.get("size"));
            count = inventoryBatchDao.findBalanceCount(param, request.getPostId());
        } else {
            resultArray = inventoryBatchDao.findBalanceMonth(param, request.getPostId(),replace, json.getString("_orderType"), request.get("page"), request.get("size"));
            count = inventoryBatchDao.findBalanceMonthCount(param, request.getPostId());
        }

        JSONObject result = new JSONObject();
        JSONArray tableHeader = getTableHeader(param);      // 获取表头数据
        result.put("tableHeader", tableHeader);

        result.put("content", resultArray);
        result.put("total", ((JSONObject) ((JSONArray) count).get(0)).get("COUNT"));
        result.put("pages", ((JSONObject) ((JSONArray) count).get(0)).get("COUNT"));
        result.put("footer", Arrays.asList(MapUtil.mapper(
                "BALANCE_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("BALANCE_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "PRICEUNIT", resultArray.stream().map(x -> Double.valueOf(x.get("PRICEUNIT").toString())).reduce(Arith::add).orElse(0.0),
                "AMOUNT", resultArray.stream().map(x -> Double.valueOf(x.get("AMOUNT").toString())).reduce(Arith::add).orElse(0.0)
        )));
        return result;
    }

    private JSONArray getTableHeader(JSONObject param) {
        JSONArray tableHeader = new JSONArray();
        tableHeader.add(MapUtil.mapper("field", "CREATE_DATE", "headerName", "日期", "width", 100));

        if ("product".equals(param.get("countType"))) {
            Map PRODUCT_NAME = MapUtil.mapper("field", "PRODUCT_NAME", "headerName", "商品", "width", 400);
            tableHeader.add(PRODUCT_NAME);
        }else{
            tableHeader.add(MapUtil.mapper("field", "CLASSIFY_NAME", "headerName", "品类", "width", 400));
        }
        tableHeader.add(MapUtil.mapper("field", "COOPERATION", "headerName", "合作方式", "width", 90));
        tableHeader.add(MapUtil.mapper("field", "PRODUCT_UOM_NAME", "headerName", "单位", "width", 90));
        tableHeader.add(MapUtil.mapper("field", "BALANCE_QTY", "headerName", "数量", "width", 90, "sum", true));
        tableHeader.add(MapUtil.mapper("field", "PRICEUNIT", "headerName", "单价", "width", 90, "sum", true));
        tableHeader.add(MapUtil.mapper("field", "AMOUNT", "headerName", "金额", "width", 90, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "PURCHASE_IN_DATE", "headerName", "入库时间", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "RESERVOIR", "headerName", "库龄(天)", "width", 90));
        tableHeader.add(MapUtil.mapper("field", "TAX", "headerName", "税率", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "COMPANY_NAME", "headerName", "公司", "width", 260));
        return tableHeader;
    }

    /**
     * 结余库存查询日月
     *
     * @param request
     * @return
     */
    public JSONObject queryDaily(SimpleRequest request) throws ParseException {
        JSONObject json = request.getJO();
        // 解析传入的条件参数，对日期格式做特殊处理
        JSONObject param = parseCondition(json.getJSONArray("condition"));

        Integer belong = Integer.valueOf(param.get("BELONG").toString());

        List<Map> resultArray;
        String orderField = json.getString("_orderField");
        String replace = StringUtils.isEmpty(orderField) ? null : orderField.replaceAll(";", ",");
        if (belong == 1) {
            resultArray = inventoryBatchDao.queryDaily(param, request.getPostId(),replace, json.getString("_orderType"));
        } else {
            resultArray = inventoryBatchDao.queryDailyMonth(param, request.getPostId(),replace, json.getString("_orderType"));
        }

        JSONArray tableHeader = getTableHeaberDaily(param, belong);
        JSONObject result = new JSONObject();
        result.put("tableHeader", tableHeader);
        result.put("content", resultArray);
        result.put("total", resultArray.size());
        result.put("footer", Arrays.asList(MapUtil.mapper(
                "LAST_BALANCE_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("LAST_BALANCE_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "LAST_BALANCE_AMT", resultArray.stream().map(x -> Double.valueOf(x.get("LAST_BALANCE_AMT").toString())).reduce(Arith::add).orElse(0.0),
                "PURCHASE_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("PURCHASE_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "PURCHASE_AMT", resultArray.stream().map(x -> Double.valueOf(x.get("PURCHASE_AMT").toString())).reduce(Arith::add).orElse(0.0),
                "PURCHASE_RETURN_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("PURCHASE_RETURN_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "PURCHASE_RETURN_AMT", resultArray.stream().map(x -> Double.valueOf(x.get("PURCHASE_RETURN_AMT").toString())).reduce(Arith::add).orElse(0.0),
                "TRAN_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("TRAN_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "TRAN_AMT", resultArray.stream().map(x -> Double.valueOf(x.get("TRAN_AMT").toString())).reduce(Arith::add).orElse(0.0),
                "SALE_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("SALE_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "SALE_AMT", resultArray.stream().map(x -> Double.valueOf(x.get("SALE_AMT").toString())).reduce(Arith::add).orElse(0.0),
                "PRICE_CHANGE_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("PRICE_CHANGE_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "PRICE_CHANGE_AMT", resultArray.stream().map(x -> Double.valueOf(x.get("PRICE_CHANGE_AMT").toString())).reduce(Arith::add).orElse(0.0),
                "PROFIT_AND_LOSS_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("PROFIT_AND_LOSS_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "PROFIT_AND_LOSS_AMT", resultArray.stream().map(x -> Double.valueOf(x.get("PROFIT_AND_LOSS_AMT").toString())).reduce(Arith::add).orElse(0.0),
                "BALANCE_QTY", resultArray.stream().map(x -> Double.valueOf(x.get("BALANCE_QTY").toString())).reduce(Arith::add).orElse(0.0),
                "BALANCE_AMT", resultArray.stream().map(x -> Double.valueOf(x.get("BALANCE_AMT").toString())).reduce(Arith::add).orElse(0.0)
        )));
        return result;
    }

    private JSONArray getTableHeaberDaily(JSONObject param, Integer belong) {
        JSONArray tableHeader = new JSONArray();
        tableHeader.add(MapUtil.mapper("field", "CREATE_DATE", "headerName", "日期", "width", 110));
        if ("product".equals(param.get("countType"))) {
            tableHeader.add(MapUtil.mapper("field", "PRODUCT_NAME", "headerName", "商品", "width", 260, "downFormatter", "data.PRODUCT_ID ? '[' + data.PRODUCT_ID + ']' + data.PRODUCT_NAME:''",
                    "valueFormatter", "data.PRODUCT_ID ? '[' + data.PRODUCT_ID + ']' + data.PRODUCT_NAME:''"));
        }
        tableHeader.add(MapUtil.mapper("field", "CLASSIFY_NAME", "headerName", "品类", "width", 150, "downFormatter", "data.CLASSIFY_ID ? '[' + data.CLASSIFY_ID + ']' + data.CLASSIFY_NAME:''",
                "valueFormatter", "data.CLASSIFY_ID ? '[' + data.CLASSIFY_ID + ']' + data.CLASSIFY_NAME:''"));
        tableHeader.add(MapUtil.mapper("field", "COOPERATION", "headerName", "合作方式", "width", 90));

        Map LAST_BALANCE_QTY = MapUtil.mapper("field", "LAST_BALANCE_QTY",
                "headerName", "数量", "width", 90, "sum", true, "headerGroup", "期初库存", "cellRenderer", "dialogButton", "valueFormatter", "number",
                "callback", "debugger;  let _STATISTIC_DATE = [data.CREATE_DATE1,data.CREATE_DATE1];" +
                        "return {'CREATE_DATE': _STATISTIC_DATE,'queryid':'surplus.inventory.queryBalance', " +
                        "'PRODUCT_ID': data.PRODUCT_ID, 'PRODUCT_ID_name': data.PRODUCT_NAME,'CLASSIFY_NAME': data.CLASSIFY_ID,'CLASSIFY_NAME_name': data.CLASSIFY_NAME," +
                        "'COOPERATION_ID':data.COOPERATION_ID,'COMPANY_ID': [data.COMPANY_ID],'COMPANY_ID_name': [data.COMPANY_NAME],'BELONG':data.BELONG};",
                "buttonList", "[{'id':'search','name':'0','action': 'link','link': 'true','api':'report/surplus.inventory','config':{'OAInterface':false,'api':'pub.query'}}]");
        tableHeader.add(LAST_BALANCE_QTY);
        tableHeader.add(MapUtil.mapper("field", "LAST_BALANCE_AMT", "headerName", "金额", "width", 90, "sum", true, "headerGroup", "期初库存", "valueFormatter", "currency"));

        String api = belong == 1 ? "'inventory.storage.number'" : "'inventory.storageMonth'";
        String formId = belong == 1 ? "'inventory.storage.number'" : "'inventory.storageMonth'";
        Map PURCHASE_QTY = MapUtil.mapper("field", "PURCHASE_QTY", "headerName", "数量", "width", 90, "sum", true, "headerGroup", "本期入库", "cellRenderer", "dialogButton", "valueFormatter", "number",
                "buttonList", "[{'id':'search','name':'本期入库','action': 'drawer','api':" + api + ",'link': '详情','formId':" + formId + " }]");
        tableHeader.add(PURCHASE_QTY);
        tableHeader.add( MapUtil.mapper("field", "PURCHASE_AMT", "headerName", "金额", "width", 90, "sum", true, "headerGroup", "本期入库", "valueFormatter", "currency"));

        String purchaseApi = belong == 1 ? "'inventory.storage.purchaseReturn'" : "'inventory.storage.purchaseReturnMonth'";
        String purchaseFormId = belong == 1 ? "'inventory.returned.number'" : "'inventory.returned.purchaseReturnMonth'";
        Map PURCHASE_RETURN_QTY = MapUtil.mapper("field", "PURCHASE_RETURN_QTY", "headerName", "数量", "width", 90, "sum", true, "headerGroup", "本期返厂", "cellRenderer", "dialogButton", "valueFormatter", "number",
                "buttonList", "[{'id':'search','name':'本期返厂','action': 'drawer','link': '详情','api':" + purchaseApi + ",'formId':" + purchaseFormId + " }]");
        tableHeader.add(PURCHASE_RETURN_QTY);
        tableHeader.add(MapUtil.mapper("field", "PURCHASE_RETURN_AMT", "headerName", "金额", "width", 90, "sum", true, "headerGroup", "本期返厂", "valueFormatter", "currency"));

        String tranApi = belong == 1 ? "'inventory.storage.findTran'" : "'inventory.storage.findTranMonth'";
        String tranFormId = belong == 1 ? "'inventory.transfers.number'" : "'inventory.transfers.findTranMonth'";
        Map TRAN_QTY = MapUtil.mapper("field", "TRAN_QTY", "headerName", "数量", "width", 90, "sum", true, "headerGroup", "本期调拨", "cellRenderer", "dialogButton", "valueFormatter", "number",
                "buttonList", "[{'id':'search','name':'本期调拨','action': 'drawer','link': '详情','api':" + tranApi + ",'formId':" + tranFormId + " }]");
        tableHeader.add(TRAN_QTY);
        tableHeader.add(MapUtil.mapper("field", "TRAN_AMT", "headerName", "金额", "width", 90, "sum", true, "headerGroup", "本期调拨", "valueFormatter", "currency"));

        String saleApi = belong == 1 ? "'inventory.storage.findSale'" : "'inventory.storage.findSaleMonth'";
        String saleFormId = belong == 1 ? "'inventory.sale.number'" : "'inventory.sale.findSaleMonth'";
        Map SALE_QTY = MapUtil.mapper("field", "SALE_QTY", "headerName", "数量", "width", 90, "sum", true, "headerGroup", "本期销售", "cellRenderer", "dialogButton", "valueFormatter", "number",
                "buttonList", "[{'id':'search','name':'本期销售','action': 'drawer','link': '详情','api':" + saleApi + ",'formId':" + saleFormId + " }]");
        tableHeader.add(SALE_QTY);
        tableHeader.add(MapUtil.mapper("field", "SALE_AMT", "headerName", "金额", "width", 90, "sum", true, "headerGroup", "本期销售", "valueFormatter", "currency"));

        String changeApi = belong == 1 ? "'inventory.storage.findPriceChange'" : "'inventory.storage.findPriceChangeMonth'";
        String changeFormId = belong == 1 ? "'inventory.change.number'" : "'inventory.change.findPriceChangeMonth'";
        Map PRICE_CHANGE_QTY = MapUtil.mapper("field", "PRICE_CHANGE_QTY","headerName", "数量", "width", 90, "sum", true, "headerGroup", "本期变价", "cellRenderer", "dialogButton", "valueFormatter", "number",
                "buttonList", "[{'id':'search','name':'本期变价','action': 'drawer','link': '详情','api':" + changeApi + ",'formId':" + changeFormId + " }]");
        tableHeader.add(PRICE_CHANGE_QTY);
        tableHeader.add(MapUtil.mapper("field", "PRICE_CHANGE_AMT", "headerName", "金额", "width", 90, "sum", true, "headerGroup", "本期变价", "valueFormatter", "currency"));

        String excessiveApi = belong == 1 ? "'inventory.storage.profitAndLoss'" : "'inventory.storage.profitAndLossMonth'";
        String excessiveFormId = belong == 1 ? "'inventory.excessive.number'" : "'inventory.excessive.profitAndLossMonth'";
        Map PROFIT_AND_LOSS_QTY = MapUtil.mapper("field", "PROFIT_AND_LOSS_QTY",
                "headerName", "数量", "width", 90, "sum", true, "headerGroup", "本期损溢", "cellRenderer", "dialogButton", "valueFormatter", "number", "buttonList", "[{" +
                        "'id':'search','name':'本期损溢','action': 'drawer','link': '详情','api':" + excessiveApi + ",'formId':" + excessiveFormId + " }]");
        tableHeader.add(PROFIT_AND_LOSS_QTY);
        tableHeader.add(MapUtil.mapper("field", "PROFIT_AND_LOSS_AMT", "headerName", "金额", "width", 90, "sum", true, "headerGroup", "本期损溢", "valueFormatter", "currency"));

        Map BALANCE_QTY = MapUtil.mapper("field", "BALANCE_QTY",
                "headerName", "数量", "width", 90, "sum", true, "headerGroup", "期末库存", "cellRenderer", "dialogButton", "valueFormatter", "number",
                "callback", "debugger;  let _STATISTIC_DATE = [data.CREATE_DATE,data.CREATE_DATE];" +
                        "return {'CREATE_DATE': _STATISTIC_DATE,'queryid':'surplus.inventory.queryBalance', " +
                        "'PRODUCT_ID': data.PRODUCT_ID, 'PRODUCT_ID_name': data.PRODUCT_NAME,'CLASSIFY_NAME': data.CLASSIFY_ID,'CLASSIFY_NAME_name': data.CLASSIFY_NAME," +
                        "'COOPERATION_ID':data.COOPERATION_ID,'COMPANY_ID': [data.COMPANY_ID],'COMPANY_ID_name': [data.COMPANY_NAME],'BELONG':data.BELONG};",
                "buttonList", "[{ 'id':'search', 'name':'0', 'action': 'link', 'link': 'true', 'api':'report/surplus.inventory','config':{'OAInterface':false,'api':'pub.query'}}]");
        tableHeader.add(BALANCE_QTY);
        tableHeader.add(MapUtil.mapper("field", "BALANCE_AMT", "headerName", "金额", "width", 90, "sum", true, "headerGroup", "期末库存", "valueFormatter", "currency"));

        tableHeader.add(MapUtil.mapper("field", "COMPANY_NAME", "headerName", "公司", "width", 260, "downFormatter", "data.COMPANY_ID ? '[' + data.COMPANY_ID + ']' + data.COMPANY_NAME:''",
                "valueFormatter", "data.COMPANY_ID ? '[' + data.COMPANY_ID + ']' + data.COMPANY_NAME:''"));
        tableHeader.add(MapUtil.mapper("field", "ERRORCHECKING", "headerName", "验错", "width", 80, "changeCellStyle", "{'text-align': 'left','backgroundColor': data.ERRORCHECKING == 1 ? '#f38181' : ''}"));
        return tableHeader;
    }
}
